<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-10-24 17:50:11
 * @version $Id$
 */

namespace app\finance\controller;
set_time_limit(0);
use think\Db;
use think\Controller;
use Godok\Org\Auth;
use think\Config;
use Payinterface\PaySdk;
use think\Log;

class Appropriation extends Base {
    
    function index(){
    	$param = request()->param();

        $pur = Db::name('purchase')->where("appropriation_status=0")->order('create_time desc')->paginate('', false, ['query'=>Request()->param()]);

        $page = $pur->render();
        $_pur = $pur->toarray()['data'];
        $purids = array_column($_pur, 'purchase_id');

        $query = Db::field('p.*,pg.*,s.supplier_name,IFNULL(pg.supplier_id,0) as supplier_id,IFNULL(pg.real_num,0) as real_num')
        ->table('sdzx_purchase')->alias('p')
        ->join('sdzx_purchase_goods pg','p.purchase_id=pg.purchase_id')
        ->join('sdzx_supplier s','pg.supplier_id=s.supplier_id','left')
        ->where("p.appropriation_status=0 and p.purchase_id in (".implode(',', $purids).")")
        ->order('p.create_time desc');

        if (isset($param['keywords']) && !empty($param['keywords'])) {
        	$query->where("p.employee_name like '%{$param['keywords']}%'");
        }
        $tmp = $query->select();
        $list = [];
        foreach ($tmp as $k => $v) {
        	if (!isset($list[$v['purchase_id']]['purchase_id'])) {
        		$list[$v['purchase_id']] = [
					'purchase_id'   => $v['purchase_id'],
					'employee_name' => $v['employee_name'],
					'employee_id'   => $v['employee_id'],
					'create_time'   => $v['create_time'],
					'list'          => [$v]
        		];
        	}else{
        		$list[$v['purchase_id']]['list'][] = $v;
        	}

        	$tmp_a = Db::name('appropriation')->where(['purchase_id'=>$v['purchase_id']])->select();
        	$list[$v['purchase_id']]['appropriation'] = $tmp_a;
        	$ent = 0; $out = 0;
        	foreach ($tmp_a as $key => $value) {
        		if ($value['type']) {
        			$ent += $value['money'];
        		}else{
        			$out += $value['money'];
        		}
        	}
        	$list[$v['purchase_id']]['ent'] = $ent;
        	$list[$v['purchase_id']]['out'] = $out;
        }

        foreach ($list as $k => $v) {
        	foreach ($v['list'] as $kk => $vv) {
        		$list[$k]['total'] += $vv['price']*$vv['num'];
        		$list[$k]['realtotal'] += $vv['cur_price']*$vv['real_num'];
                $list[$k]['_list'][$vv['supplier_id']]['list'][] = $vv;
                $list[$k]['_list'][$vv['supplier_id']]['total'] += $vv['cur_price']*$vv['real_num'];
        	}

        }

        $_tlist = [];
        foreach ($list as $k => $v) {
            $_tlist[date('Y-m-d',strtotime($v['create_time']))]['time'] = date('Y-m-d',strtotime($v['create_time']));
            $_tlist[date('Y-m-d',strtotime($v['create_time']))]['list'][] = $v;
            $_tlist[date('Y-m-d',strtotime($v['create_time']))]['total'] += $v['total'];
            $_tlist[date('Y-m-d',strtotime($v['create_time']))]['realtotal'] += $v['realtotal'];
        }
        $arr = ['list'=>$_tlist,'page'=>$page];
        return $this->fetch('',$arr);
    }

    public function agree()
    {
    	$param = request()->param();
    	if (!isset($param['money']) || empty($param['money']) || !is_numeric($param['money']) || $param['money']<0) {
    		$this->error('请正确填写拨款金额');
    	}

    	$pur = Db::name('purchase')->where(['purchase_id'=>$param['id']])->find();

    	$pg = Db::field('sum(price*num) as money')
    	->name('purchase_goods')
        ->where("purchase_id={$param['id']}")
        ->find();

    	$data = [
			'create_time'    => date('Y-m-d H:i:s'),
			'employee_name'  => $pur['employee_name'],
			'employee_id'    => $pur['employee_id'],
			'purchase_id'    => $pur['purchase_id'],
			'purchase_money' => $pg['money'],
			'money'          => $param['money'],
			'type'           => 0,
    	];

    	$re = Db::name('appropriation')->insertGetId($data);
    	if ($re) {
    		$this->success('操作成功');
    	}else{
    		$this->error('操作失败');
    	}
    }

    public function refund()
    {
    	$param = request()->param();
    	if (!isset($param['money']) || empty($param['money']) || !is_numeric($param['money']) || $param['money']<0) {
    		$this->error('请正确填写退款金额');
    	}

    	$pur = Db::name('purchase')->where(['purchase_id'=>$param['id']])->find();

    	$pg = Db::field('sum(price*num) as money')
    	->name('purchase_goods')
        ->where("purchase_id={$param['id']}")
        ->find();

    	$data = [
			'create_time'    => date('Y-m-d H:i:s'),
			'employee_name'  => $pur['employee_name'],
			'employee_id'    => $pur['employee_id'],
			'purchase_id'    => $pur['purchase_id'],
			'purchase_money' => $pg['money'],
			'money'          => $param['money'],
			'type'           => 1,
    	];

    	$re = Db::name('appropriation')->insertGetId($data);
    	if ($re) {
    		$this->success('操作成功');
    	}else{
    		$this->error('操作失败');
    	}
    }

    public function finish()
    {
    	$param = request()->param();
    	$re = Db::name('purchase')->where(['purchase_id'=>$param['id']])->update(['appropriation_status'=>1]);
    	$this->success('操作成功');
    }

    public function history()
    {
    	$param = request()->param();

        $pur = Db::name('purchase')->where("appropriation_status=1")->order('create_time desc')->paginate('', false, ['query'=>Request()->param()]);

        $page = $pur->render();
        $_pur = $pur->toarray()['data'];
        $purids = array_column($_pur, 'purchase_id');

        $query = Db::field('p.*,pg.*,s.supplier_name,IFNULL(pg.supplier_id,0) as supplier_id,IFNULL(pg.real_num,0) as real_num')
        ->table('sdzx_purchase')->alias('p')
        ->join('sdzx_purchase_goods pg','p.purchase_id=pg.purchase_id')
        ->join('sdzx_supplier s','pg.supplier_id=s.supplier_id','left')
        ->where("p.appropriation_status=1 and p.purchase_id in (".implode(',', $purids).")")
        ->order('p.create_time desc');

        if (isset($param['keywords']) && !empty($param['keywords'])) {
            $query->where("p.employee_name like '%{$param['keywords']}%'");
        }
        $tmp = $query->select();
        $list = [];
        foreach ($tmp as $k => $v) {
            if (!isset($list[$v['purchase_id']]['purchase_id'])) {
                $list[$v['purchase_id']] = [
                    'purchase_id'   => $v['purchase_id'],
                    'employee_name' => $v['employee_name'],
                    'employee_id'   => $v['employee_id'],
                    'create_time'   => $v['create_time'],
                    'list'          => [$v]
                ];
            }else{
                $list[$v['purchase_id']]['list'][] = $v;
            }

            $tmp_a = Db::name('appropriation')->where(['purchase_id'=>$v['purchase_id']])->select();
            $list[$v['purchase_id']]['appropriation'] = $tmp_a;
            $ent = 0; $out = 0;
            foreach ($tmp_a as $key => $value) {
                if ($value['type']) {
                    $ent += $value['money'];
                }else{
                    $out += $value['money'];
                }
            }
            $list[$v['purchase_id']]['ent'] = $ent;
            $list[$v['purchase_id']]['out'] = $out;
        }

        foreach ($list as $k => $v) {
            foreach ($v['list'] as $kk => $vv) {
                $list[$k]['total'] += $vv['price']*$vv['num'];
                $list[$k]['realtotal'] += $vv['cur_price']*$vv['real_num'];
                $list[$k]['_list'][$vv['supplier_id']]['list'][] = $vv;
                $list[$k]['_list'][$vv['supplier_id']]['total'] += $vv['cur_price']*$vv['real_num'];
            }
        }
        
        $_tlist = [];
        foreach ($list as $k => $v) {
            $_tlist[date('Y-m-d',strtotime($v['create_time']))]['time'] = date('Y-m-d',strtotime($v['create_time']));
            $_tlist[date('Y-m-d',strtotime($v['create_time']))]['list'][] = $v;
            $_tlist[date('Y-m-d',strtotime($v['create_time']))]['total'] += $v['total'];
            $_tlist[date('Y-m-d',strtotime($v['create_time']))]['realtotal'] += $v['realtotal'];
        }

        $arr = ['list'=>$_tlist,'page'=>$page];
        return $this->fetch('',$arr);
    }
}